<template>
    <view>
        <!-- 活动轮播图 -->
        <uni-swiper-dot class="uni-list-cell-db" :info="new Array(activityItemsBanners.length)" :current="current" mode="round">
            <swiper autoplay class="swiper-box" :current="swiperDotIndex" @change="change">
                <swiper-item v-for="(item, index) in activityItemsBanners" :key="index">
                    <view class="swiper-item">
                        <image mode="widthFix" style="width: 100%" :src="organizationGateway + '/file/download?filepath=' + item.info.mmUrl" class="img"> </image>
                    </view>
                </swiper-item>
            </swiper>
        </uni-swiper-dot>

        <view class="detail-title">
            <view style="flex: 1; display: flex; margin-top: 4px">
                <view style="color: #fff; font-weight: 400" v-if="getCountDown(activity.gpReti) < 0 && getCountDown(activity.gpStti) > 0">
                    ￥{{ activityItem?.giGppr?.substring(0, 1) + getNumIndex(activityItem?.giGppr) }}
                </view>
                <view style="color: #fff; font-weight: 400" v-else>￥{{ numberFormat(activityItem?.giGppr || 0, 0) }} </view>
                <view style="color: #fff; text-decoration: line-through; margin: 3px 10px 0 10px; font-size: 12px"> ￥{{ numberFormat(activityItem?.giInpr || 0, 0) }}</view>
                <uni-tag v-if="activityItem?.giGrou === true" :text="activityItem?.giGrpe + '人团'" type="error" :circle="true" size="small"></uni-tag>
            </view>
            <view style="margin-top: 7px; font-size: 13px; color: #fff" v-if="getCountDown(activity.gpReti) < 0 && getCountDown(activity.gpStti) > 0">
                <text>{{ activityItem?.giBoqu || 0 }} 人预约</text>
            </view>
            <view style="display: flex; margin-top: 7px; font-size: 13px; color: #fff" v-else>
                <view> {{ activityItem?.giSaqu || 0 }} 人购买 </view>
                <view style="margin: 0 10px"> | </view>
                <view>
                    仅剩
                    {{ Number(activityItem?.giWaqu) - Number(activityItem?.giBoqu) - Number(activityItem?.giSaqu) || 0 }}
                    件
                </view>
            </view>
        </view>

        <view class="mb-title">{{ activityItem?.giName }}</view>
        <uni-card :is-shadow="false" is-full padding="15px 0">
            <view style="position: relative">
                <view style="font-size: 12px; display: flex" v-if="getCountDown(activity.gpReti) < 0 && getCountDown(activity.gpStti) > 0">
                    <view style="font-size: 14px">活动开始倒计时：</view>
                    <view style="margin-top: -5px">
                        <uni-countdown :font-size="12" :second="getCountDown(activity.gpStti)" color="#FFFFFF" background-color="#c1a173" :show-colon="false" />
                    </view>
                </view>
                <view style="font-size: 12px; display: flex" v-else-if="getCountDown(activity.gpStti) <= 0 && getCountDown(activity.gpEnti) >= 0">
                    <view style="font-size: 14px">活动结束倒计时：</view>
                    <view style="margin-top: -5px">
                        <uni-countdown :font-size="12" :second="getCountDown(activity.gpEnti)" color="#FFFFFF" background-color="#c1a173" :show-colon="false" />
                    </view>
                </view>
                <view style="font-size: 12px; display: flex" v-else="getCountDown(activity.gpEnti) < 0">
                    <view style="font-size: 14px">活动结束倒计时：</view>
                    <view style="margin-top: -5px">
                        <uni-countdown :font-size="12" :second="0" color="#FFFFFF" background-color="#c1a173" :show-colon="false" />
                    </view>
                </view>

                <view class="detail-share-btn" @click="openShareShow()"> 分享 </view>
            </view>
        </uni-card>

        <view style="margin-bottom: 5px"></view>

        <uni-section v-if="activityItemStores?.filter((item) => activityStores?.findIndex((_item) => item.osUuid === _item.osUuid) !== -1).length > 0" title="适用门店" type="line" padding="0">
            <uni-list>
                <uni-list-item v-for="(item, index) in activityItemStores?.filter((item) => activityStores?.findIndex((_item) => item.osUuid === _item.osUuid) !== -1)">
                    <template v-slot:header>
                        <uni-badge :text="index + 1" type="primary" size="normal" />
                    </template>
                    <template v-slot:body>
                        <view class="slot-text">
                            <view style="font-size: 14px; margin-left: 5px">{{ item.osName }}</view>
                            <view style="font-size: 12px; margin-left: 5px; color: #a1a3a6; width: 220px">
                                {{ item.osZoad + "/" + item.osDead }}
                            </view>
                        </view>
                    </template>
                    <template v-slot:footer>
                        <view style="display: flex">
                            <view style="font-size: 12px; text-align: right; width: 30px" @click="phoneCall(item.osPhon)">
                                <uni-icons type="phone" size="24"></uni-icons>
                            </view>
                            <view style="font-size: 12px; text-align: right; width: 30px" @click="mapLocation(Number(item.osCoox), Number(item.osCooy))">
                                <uni-icons type="location" size="24"></uni-icons>
                            </view>
                        </view>
                    </template>
                </uni-list-item>
            </uni-list>
        </uni-section>

        <view style="margin-bottom: 5px"></view>

        <view v-if="spGiUuid !== activityItem.giUuid">
            <uni-section v-if="allSpellOrder.length > 0" :title="allSpellOrder.length + '人在拼单，可直接参与'" type="line" padding="0">
                <template v-slot:right><text v-if="allSpellOrder.length > 3" @click="gotoMoreSpellOrders()">查看更多</text></template>
                <uni-list>
                    <uni-list-item v-for="(item, index) in spellOrders">
                        <!-- 自定义 header -->
                        <template v-slot:header>
                            <view style="flex: 1; display: flex; align-items: center">
                                <image style="width: 40px; height: 40px; border-radius: 20px" :src="item.ggAvat" mode="widthFix"></image>
                                <view style="margin-left: 8px; font-size: 13px">{{ item.ggWcna }}</view>
                            </view>
                        </template>
                        <!-- 自定义 body -->
                        <template v-slot:body>
                            <view class="slot-text">
                                <view>还差{{ Number(item.ggQuat) - Number(item.members?.totalCount) }}人拼成</view>
                                <view style="display: flex">
                                    <text>剩余:</text>
                                    <uni-countdown :show-day="false" :second="86400" />
                                </view>
                            </view>
                        </template>
                        <!-- 自定义 footer-->
                        <template v-slot:footer>
                            <view @click="authorization(item)">
                                <u-button size="small" customStyle="background-color:#CD5555; color: #fff">去拼单</u-button>
                            </view>
                        </template>
                    </uni-list-item>
                </uni-list>
            </uni-section>
        </view>

        <view style="margin-bottom: 5px"> </view>

        <uni-section v-if="activityItem?.services?.nodes?.length > 0" title="服务清单" type="line" padding="0">
            <uni-list>
                <uni-list-item v-for="(item, index) in activityItem?.services?.nodes">
                    <template v-slot:header>
                        <uni-badge :text="index + 1" type="warning" size="normal" />
                    </template>
                    <template v-slot:body>
                        <view class="slot-text">
                            <view style="font-size: 14px; margin-left: 5px">{{ item?.info?.siName }} </view>
                            <view style="font-size: 12px; margin-left: 5px; color: #a1a3a6; width: 220px">
                                {{ item?.info?.siCont }}
                            </view>
                        </view>
                    </template>
                    <template v-slot:footer>
                        <view>
                            <view style="font-size: 12px; text-align: right"> ￥{{ numberFormat(item?.siPric, 2) }} </view>
                            <view style="font-size: 12px; text-align: right">
                                {{ item?.info?.siUnsu + "/" + item?.info?.siUnit }}
                            </view>
                        </view>
                    </template>
                </uni-list-item>
            </uni-list>
        </uni-section>

        <view style="margin-bottom: 5px"></view>

        <uni-section v-if="activityItem?.commodities?.nodes?.length > 0" title="商品清单" type="line" padding="0" style="margin-bottom: 10px">
            <uni-list>
                <uni-list-item v-for="(item, index) in activityItem?.commodities?.nodes">
                    <template v-slot:header>
                        <uni-badge :text="index + 1" type="success" size="normal" />
                    </template>
                    <template v-slot:body>
                        <view class="slot-text">
                            <view style="font-size: 14px; margin-left: 5px">
                                {{ item?.info?.ciAlna || "商品名称" }}
                            </view>
                            <view style="font-size: 12px; margin-left: 5px; color: #a1a3a6; width: 220px">
                                {{ item?.info?.ciDesc || "商品描述" }}
                            </view>
                        </view>
                    </template>
                    <template v-slot:footer>
                        <view>
                            <view style="font-size: 12px; text-align: right"> ￥{{ numberFormat(item?.ciMava, 2) }} </view>
                        </view>
                    </template>
                </uni-list-item>
            </uni-list>
        </uni-section>

        <view style="margin-bottom: 5px"></view>

        <view>
            <image v-for="(item, index) in graphicDetails" mode="widthFix" style="width: 100%" :src="organizationGateway + '/file/download?filepath=' + item.info.mmUrl"></image>
        </view>

        <view class="actions">
            <view class="item menu" @click="goHome()">
                <uni-icons type="home" size="24"></uni-icons>
                <view>首页</view>
            </view>
            <view class="item menu" @click="openShareShow()">
                <uni-icons type="redo" size="24"></uni-icons>
                <view>分享</view>
            </view>

            <view v-if="getCountDown(activity.gpReti) < 0 && getCountDown(activity.gpStti) > 0">
                <view v-if="appoint?.gaApid">
                    <view style="width: 150px">
                        <u-button type="warning" text="已预约" disabled></u-button>
                    </view>
                </view>

                <view v-else>
                    <view style="width: 150px">
                        <u-button type="warning" text="预约" @click="authorization('appointment')"> </u-button>
                    </view>
                </view>
            </view>

            <view v-else-if="getCountDown(activity.gpStti) <= 0 && getCountDown(activity.gpEnti) >= 0">
                <view v-if="ggUuid && spGiUuid === activityItem.giUuid">
                    <view style="width: 150px">
                        <u-button type="warning" text="加入拼团" @click="authorization('joinGroup')"></u-button>
                    </view>
                </view>

                <view v-else>
                    <view style="flex: 1; display: flex; padding-top: 4px">
                        <view style="flex: 1; margin-left: 3px; width: 120px">
                            <u-button
                                type="error"
                                :text="'￥' + numberFormat(activityItem.giSppr, 0) + '\n单独购买'"
                                color="linear-gradient(to right, rgb(66, 83, 216), rgb(213, 51, 186))"
                                @click="authorization('alone')"
                            ></u-button>
                        </view>
                        <view style="flex: 1; margin-left: 3px; width: 120px" v-if="activityItem?.giGrou === true">
                            <u-button type="warning" :text="'￥' + numberFormat(activityItem.giGppr, 0) + '\n拼团购买'" @click="authorization('group')"> </u-button>
                        </view>
                    </view>
                </view>
            </view>
            <view v-else="getCountDown(activity.gpEnti) < 0">
                <view style="width: 150px">
                    <u-button type="warning" text="活动已结束" disabled></u-button>
                </view>
            </view>
        </view>

        <uni-popup ref="popup_share" background-color="#fff">
            <view style="text-align: center; color: #4f5555; margin: 15px 0">分享到</view>
            <view class="share-button" style="display: flex; justify-content: space-between; align-items: center">
                <view style="text-align: center; padding: 10px 0 10px 60px">
                    <button open-type="share" hover-class="none" style="text-align: center">
                        <image class="share-icon" src="../../static/icons/wechat.png"></image>
                    </button>
                    <view style="margin-bottom: 10px">分享给好友</view>
                </view>

                <view style="text-align: center; margin: 0 60px 10px 0" @click="handlePoster()">
                    <image class="share-icon" src="../../static/icons/friend.png"></image>
                    <view>分享到朋友圈</view>
                </view>
            </view>
        </uni-popup>

        <view>
            <u-modal :show="isOpened" confirmText="保存到相册" cancelText="关闭显示" showCancelButton="true" width="350px" @confirm="saveImg()" @cancel="colsePos()">
                <canvas style="width: 310px; height: 430px" canvas-id="myCanvas"></canvas>
            </u-modal>
        </view>

        <!-- 授权微信手机号弹窗 -->
        <uni-popup ref="popup_phone" background-color="#fff">
            <view style="padding: 30px">
                <button type="primary" open-type="getPhoneNumber" @getphonenumber="(e) => decryptPhoneNumber(e, $store, $refs, appid, activity)">微信一键授权</button>
            </view>
        </uni-popup>

        <!-- 下单 -->
        <uni-popup ref="popup_order" background-color="#fff">
            <order-popup :activityItem="activityItem" :appointment="appoint" :orderType="orderType" :closePopup="closePopup" :callback="submitOrderCallback" />
        </uni-popup>
    </view>
</template>

<script>
import { mapGetters } from "vuex";

import {
    getWxCode,
    getWxPhoneNumber,
    getCustomerByCiPhon,
    createCustomers,
    createPlatformConsumerInfo,
    createCustomerLoginRelationship,
    updateCustomerByCiUuid,
    mergeGuestToCustomer,
    createItemAppointment,
    getCustOrderBySoCuidAndSoItem,
    createActivityItemSpellOrder,
} from "../../utils/api.js";
import { numberFormat, userAuthorization, saveShareRecord, pageBrowseStart, pageBrowseEnd } from "../../utils/helper";

export default {
    data() {
        return {
            giUuid: "",
            gpUuid: "",
            isOpened: false,
            posterImg: "",
            appoint: {},
            spellOrders: [],
            orderType: "",
            isBrowse: false,
            pageUserInfo: {},
            current: 0,
            authInfo: ""
        };
    },

    async onLoad(params) {
        // 页面传参 params
        // uni.setEnableDebug({
        //     enableDebug: true,
        // });
        this.gpUuid = params.gpUuid || "";
        this.giUuid = params.giUuid || "";

        if (params.isJump && params.giUuid && params.gpUuid) {
            if (params.ggUuid) {
                this.$store.dispatch("personInfo/saveParams", {
                    staffId: params.staffId || "",
                    shareId: params.shareId || "",
                });
                this.$store.dispatch("personInfo/save", {
                    ggUuid: params.ggUuid || "",
                    spGiUuid: params.giUuid || "",
                });
            } else {
                this.$store.dispatch("personInfo/saveParams", {
                    staffId: params.staffId || "",
                    shareId: params.shareId || "",
                });
            }

            this.$store.dispatch("activityInfo/loadActivity", {});
            this.$store.dispatch("activityInfo/loadCurrentActivityItem", {
                gpUuid: params.gpUuid,
                giUuid: params.giUuid,
            });
        }
        wx.showShareMenu({
            withShareTicket: true,
            menus: ["shareAppMessage", "shareTimeline"],
        });

        let userInfo = uni.getStorageSync("userInfo");
        if (userInfo?.openId && this.gpUuid && params.isJump === "yes" && userInfo?.isLogin === true) {
            this.$store.dispatch("activityInfo/getItemAppointment", {
                gpUuid: params.gpUuid,
                gaApid: userInfo.ciUuid,
            });
            let rlData = {
                gpUuid: this.gpUuid,
                ciUuid: userInfo.ciUuid,
                clTime: new Date().getUTCTime(),
            };
            if (params.shareId) rlData.scUuid = params.shareId;
            if (params.staffId) rlData.orUuid = params.staffId;
            if (params.shareId || params.staffId) {
                createCustomerLoginRelationship(rlData);
            }
        }
    },

    onHide() {
        pageBrowseEnd(this.pageUserInfo.gbUuid, this.pageUserInfo.gbInti);
        this.isBrowse === false;
    },

    computed: {
        ...mapGetters({
            appid: "globalInfo/appid",
            merchantStores: "globalInfo/merchantStores",
            organizationGateway: "globalInfo/organizationGateway",
            globalUserInfo: "personInfo/userInfo",
            activity: "activityInfo/activity",
            activityStores: "activityInfo/activityStores",
            activityItem: "activityInfo/currentActivityItem",
            activityItemStores: "activityInfo/currentActivityItemStores",
            activityItemsBanners: "activityInfo/currentActivityItemBanners",
            graphicDetails: "activityInfo/currentActivityItemGraphicDetails",
            allSpellOrder: "activityInfo/currentActivityItemSpellOrders", //所有拼团信息
            appointment: "activityInfo/appointment",
            ggUuid: "personInfo/ggUuid",
            spGiUuid: "personInfo/spGiUuid",
            defaultImageBase64: "globalInfo/defaultImageBase64",
        }),
    },

    watch: {
        globalUserInfo: {
            handler(newValue, oldValue) {
                if (newValue?.openId && newValue?.ciUuid && this.activity.gpUuid)
                    this.$store.dispatch("activityInfo/getItemAppointment", {
                        gpUuid: this.activity.gpUuid,
                        gaApid: newValue.ciUuid,
                    });
            },
            immediate: true,
            deep: true,
        },
        allSpellOrder: {
            handler(newValue, oldValue) {
                this.spellOrders = JSON.parse(JSON.stringify(newValue));
                if (newValue.length > 3) {
                    this.spellOrders.length = 3;
                }
            },
            immediate: true,
            deep: true,
        },
        appointment: {
            handler(newValue, oldValue) {
                this.appoint = newValue.find((item) => item.giUuid === this.activityItem?.giUuid) || {};
            },
            immediate: true,
            deep: true,
        },
        activityItem: {
            async handler(newValue, oldValue) {
                if (this.isBrowse === false && newValue.gpUuid) {
                    let res = await pageBrowseStart(this.$store, newValue.giName, this.activity, newValue); // 浏览记录
                    if (res.ciUuid) {
                        this.isBrowse = true;
                        this.pageUserInfo = res;
                    }
                }
            },
            immediate: true,
            deep: true,
        },
    },

    // 转发
    onShareAppMessage(res) {
        let gpUuid = this.activity?.gpUuid || "";
        let giUuid = this.activityItem?.giUuid || "";
        const { staffId, shUuid } = saveShareRecord(gpUuid);
        return {
            title: this.activityItem?.giName,
            path: `/pages/activities/detail?isJump=yes&giUuid=${giUuid}&shareId=${shUuid}&gpUuid=${gpUuid}&staffId=${staffId}`,
            imageUrl: this.organizationGateway + "/file/download?filepath=" + this.activityItemsBanners[0].info.mmUrl,
        };
    },

    // 朋友圈
    onShareTimeline(res) {
        let gpUuid = this.activity?.gpUuid || "";
        let giUuid = this.activityItem?.giUuid || "";
        const { staffId, shUuid } = saveShareRecord(gpUuid);
        return {
            title: this.activityItem?.giName,
            imageUrl: this.organizationGateway + "/file/download?filepath=" + this.activityItemsBanners[0].info.mmUrl,
            query: `isJump=yes&giUuid=${giUuid}&shareId=${shUuid}&gpUuid=${gpUuid}&staffId=${staffId}`,
        };
    },

    methods: {
        phoneCall(phone) {
            uni.makePhoneCall({
                phoneNumber: phone,
            });
        },

        change(e) {
            this.current = e.detail.current;
        },

        mapLocation(osCoox, osCooy) {
            uni.openLocation({
                latitude: osCoox,
                longitude: osCooy,
            });
        },

        openShareShow() {
            this.$refs.popup_share.open("bottom");
        },

        goHome() {
            uni.switchTab({
                url: "/pages/home/index",
            });
        },

        async getWxCode() {
            const fs = uni.getFileSystemManager();
            const filePath = `${wx.env.USER_DATA_PATH}/${this.activityItem.giUuid}.png`;
            try {
                fs.accessSync(filePath);
            } catch (e) {
                let pages = getCurrentPages();
                let currPage = pages[pages.length - 1];
                let userInfo = uni.getStorageSync("userInfo") || "";
                let staffId = uni.getStorageSync("staffId") || ""; // 员工Id
                let shUuid = userInfo?.ciUuid || "";
                let res = await getWxCode({
                    appid: this.appid,
                    page: currPage.route,
                    scene: this.activityItem.giUuid,
                });
                if (res) {
                    // 将返回的图片buffer生成图片，并保存至临时用户文件中
                    fs.writeFileSync(filePath, res, "base64");
                }
            }

            return filePath;
        },

        handlePoster() {
            let userInfo = uni.getStorageSync("userInfo");
            let nickName = userInfo.nickName;
            let itemImage = this.getActivityItemImage(this.activityItem.giPrph);
            this.$refs.popup_share.close();
            uni.showLoading({
                title: "海报生成中",
                mask: true,
            });
            uni.downloadFile({
                url: itemImage,
                success: (res) => {
                    let bgImg = res.tempFilePath;
                    uni.downloadFile({
                        url: userInfo.avatarUrl,
                        success: async (res1) => {
                            let codeImg = await this.getWxCode();
                            let avatar = res1.tempFilePath;
                            await this.drawPoster(bgImg, avatar, codeImg, nickName);
                            uni.hideLoading();
                        },
                    });
                },
            });
        },

        drawPoster(bgImg, avatar, codeImg, nickName) {
            let _this = this;
            _this.isOpened = true;
            let ctx = uni.createCanvasContext("myCanvas", _this);
            // 绘制背景
            ctx.setFillStyle("#f58220");
            ctx.fillRect(10, 10, 290, 410);

            // 绘制头像
            ctx.save();
            ctx.beginPath();
            ctx.arc(40 / 2 + 25, 40 / 2 + 25, 40 / 2, 0, Math.PI * 2, false);
            ctx.clip();
            ctx.drawImage(avatar, 25, 25, 40, 40);
            ctx.restore();

            //绘制名称
            ctx.setFontSize(14);
            ctx.setFillStyle("#fffffb");
            ctx.fillText(nickName, 70, 40);
            ctx.setFontSize(12);
            ctx.fillText("超级惊喜，不期而遇", 70, 58);

            //绘制中央区域
            ctx.save();
            ctx.setFillStyle("#fffffb");
            ctx.setLineJoin("round"); //交点设置成圆角
            ctx.setLineWidth(16);
            ctx.setStrokeStyle("#fffffb");
            ctx.strokeRect(30, 80, 250, 320);
            ctx.fillRect(35, 75, 250, 320);
            ctx.closePath();
            ctx.restore();

            // 绘制中央区域图片
            ctx.drawImage(bgImg, 30, 80, 250, 230);

            // 绘制价格
            ctx.setFontSize(12);
            ctx.setFillStyle("#999d9c");
            ctx.fillText(`原价：${_this.activityItem?.giInpr}`, 30, 350);
            ctx.beginPath();
            ctx.rect(30, 345, 82, 2);
            ctx.fill();

            ctx.font = "normal bold 20px 宋体";
            ctx.setFillStyle("red");
            ctx.fillText(`￥${_this.activityItem?.giGppr}`, 30, 333);

            // 绘制项目名称
            ctx.setFillStyle("#130c0e");
            ctx.font = "normal normal 14px 宋体";
            const str = _this.activityItem?.giName;
            _this.toFormateStr(ctx, str, 135, 2, 32, 374, 21);

            // 绘制小程序码
            ctx.drawImage(codeImg, 200, 325, 65, 65);
            ctx.draw();
            //将生成好的图片保存到本地，需要延迟一会，绘制期间耗时
            setTimeout(function () {
                uni.canvasToTempFilePath({
                    canvasId: "myCanvas",
                    success: function (res) {
                        let tempFilePath = res.tempFilePath;
                        _this.posterImg = tempFilePath;
                    },
                    fail: function (res) {
                        console.log(res);
                    },
                });
            }, 200);
        },

        toFormateStr(ctx, str, draw_width, lineNum, startX, startY, steps) {
            let drawWidth = ctx.measureText(str).width;
            let strLN = drawWidth / draw_width;
            let drawLine = Math.ceil(strLN); //行数
            let strLen = parseInt(str.length / strLN); //每行字数
            let startPoint = startY;

            if (drawWidth < draw_width) {
                ctx.fillText(str, startX, startY);
            } else {
                for (let i = 0; i < drawLine; i++) {
                    let startStr = strLen * i;
                    if (i + 1 < lineNum) {
                        ctx.fillText(str.substring(startStr, startStr + strLen), startX, startPoint);
                    }
                    if (i + 1 == lineNum) {
                        ctx.fillText(str.substring(startStr, startStr + strLen), startX, startPoint);
                    }
                    startPoint += steps;
                }
            }
        },

        saveImg() {
            uni.saveImageToPhotosAlbum({
                filePath: this.posterImg,
                success: (res) => {
                    uni.showToast({
                        title: "已保存到相册",
                        icon: "success",
                        duration: 3000,
                    });
                },
                fail: async (err) => {
                    if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
                        const ret = await uni.getSetting();
                        if (ret.authSetting["scope.writePhotosAlbum"]) {
                            uni.showToast({
                                title: "已授权",
                                icon: "success",
                            });
                        }
                        if (ret.authSetting["scope.writePhotosAlbum"] == false) {
                            uni.showModal({
                                title: "提示",
                                content: "图片保存失败，请前往设置页面允许保存相册",
                                confirmColor: "#8C5CDD",
                                success: function (res) {
                                    if (res.confirm) {
                                        uni.openSetting({
                                            success(res) {
                                                console.log(res);
                                            },
                                        });
                                    }
                                    if (res.cancel) {
                                        uni.showToast({
                                            title: "取消",
                                            icon: "error",
                                        });
                                    }
                                },
                            });
                        }
                    }
                },
            });
        },

        colsePos() {
            this.isOpened = false;
        },

        async authorization(item) {
            this.authInfo = item
            let userInfo = uni.getStorageSync("userInfo");
            
            if (userInfo?.openId) {
                if (userInfo.phone) {
                    if (item === "alone") {
                        this.orderType = "单独购买";
                        this.onAlonePurchase();
                    }

                    if (item === "group") {
                        this.orderType = "新团订单";
                        this.onSpellOrder();
                    }

                    if (item === "appointment") this.handleItemAppointment(); //预约项目

                    if (item.ggUuid) {
                        this.orderType = "拼团订单";
                        this.handleGoToSpellOrder(item); //去拼团页面
                    }

                    if (item === "joinGroup") {
                        this.orderType = "参团拼单";
                        this.handleJoinSpellOrder(); //分享后加入拼团
                    }
                } else {
                    this.$refs.popup_phone.open("bottom");
                }
            } else {
                let user = await userAuthorization(this.activity.gpUuid);
                if (user) {
                    this.$store.dispatch("personInfo/save", {
                        userInfo: user,
                    });
                    if (user?.phone) {
                        if (item === "alone") {
                            this.orderType = "单独购买";
                            this.onAlonePurchase();
                        }
                        
                        if (item === "group") {
                            this.orderType = "新团订单";
                            this.onSpellOrder();
                        }
                        
                        if (item === "appointment") this.handleItemAppointment(); //预约项目
                        
                        if (item.ggUuid) {
                            this.orderType = "拼团订单";
                            this.handleGoToSpellOrder(item); //去拼团页面
                        }

                        if (item === "joinGroup") {
                            this.orderType = "参团拼单";
                            this.handleJoinSpellOrder(); //分享后加入拼团
                        }
                    }else this.$refs.popup_phone.open("bottom");
                }
            }
        },

        async decryptPhoneNumber(e, $store, $refs, appid, activity) {
            $refs.popup_phone.close();
            if (e.detail.errMsg !== "getPhoneNumber:ok") return;

            let userInfo = uni.getStorageSync("userInfo"); // 用户信息

            let brwseData = {
                ciUuid: userInfo.ciUuid,
            };

            const phoneInfo = await getWxPhoneNumber({
                appid,
                ...e.detail,
            });
            if (!phoneInfo?.phone_info?.phoneNumber)
                return uni.showToast({
                    title: "没获取到手机号",
                    icon: "error",
                    duration: 2000,
                });

            let resCust = await getCustomerByCiPhon({
                ciPhon: phoneInfo.phone_info.phoneNumber,
            });
            let shareId = uni.getStorageSync("shareId") || ""; // 分享人ID
            let staffId = uni.getStorageSync("staffId") || ""; // 员工ID

            if (!resCust?.ciUuid) {
                let data = {
                    ciPhon: phoneInfo.phone_info.phoneNumber,
                    ciAvat: userInfo.avatarUrl,
                    ciFrom: "新客",
                    ciCity: userInfo.city,
                    ciPrin: userInfo.province,
                    ciAlia: userInfo.nickName,
                    openId: userInfo.openId,
                    appId: appid,
                    orUuid: staffId || null,
                };
                let resId = await createCustomers(data);

                if (resId) {
                    userInfo.ciUuid = resId?.ciUuid;
                    userInfo.phone = phoneInfo.phone_info.phoneNumber;
                    userInfo.isNew = true;
                    userInfo.isLogin = true;

                    $store.dispatch("personInfo/save", {
                        userInfo,
                    });

                    createPlatformConsumerInfo({
                        ciAlia: userInfo.nickName,
                        ciAvat: userInfo.avatarUrl,
                        ciPhon: userInfo.phone,
                        appId: appid,
                        openId: userInfo.openId,
                    });

                    let rlData = {
                        gpUuid: activity.gpUuid,
                        ciUuid: userInfo.ciUuid,
                        clTime: new Date().getUTCTime(),
                    };

                    if (shareId) rlData.scUuid = shareId;
                    if (staffId) rlData.orUuid = staffId;

                    if (staffId || shareId) {
                        createCustomerLoginRelationship(rlData);
                    }
                }
            } else {
                let data = {
                    ciUuid: resCust?.ciUuid,
                    ciPhon: phoneInfo.phone_info.phoneNumber,
                    ciAvat: userInfo.avatarUrl,
                    ciCity: userInfo.city,
                    ciPrin: userInfo.province,
                    ciAlia: userInfo.nickName,
                    openId: userInfo.openId,
                    appId: appid,
                };

                let res1 = await updateCustomerByCiUuid(data);

                if (res1) {
                    userInfo.ciUuid = resCust?.ciUuid;
                    userInfo.phone = phoneInfo.phone_info.phoneNumber;
                    userInfo.isNew = resCust?.ciFrom === "新客" ? true : false;
                    userInfo.ciName = resCust?.ciName;
                    userInfo.isLogin = true;

                    $store.dispatch("personInfo/save", {
                        userInfo,
                    });

                    createPlatformConsumerInfo({
                        ciAlia: userInfo.nickName,
                        ciAvat: userInfo.avatarUrl,
                        ciPhon: userInfo.phone,
                        appId: appid,
                        openId: userInfo.openId,
                    });

                    let rlData = {
                        gpUuid: activity.gpUuid,
                        ciUuid: userInfo.ciUuid,
                        clTime: new Date().getUTCTime(),
                    };
                    if (shareId) rlData.scUuid = shareId;
                    if (staffId) rlData.orUuid = staffId;
                    if (staffId || shareId) {
                        createCustomerLoginRelationship(rlData);
                    }
                }
            }

            brwseData.ciUuidNew = userInfo.ciUuid;
            brwseData.ciAlia = userInfo.nickName;
            brwseData.ciType = userInfo.isNew ? "新客" : "老客";

            mergeGuestToCustomer(brwseData);
            
            if (this.authInfo === "alone") {
            	this.orderType = "单独购买";
            	this.onAlonePurchase();
            }
            
            if (this.authInfo === "group") {
            	this.orderType = "新团订单";
            	this.onSpellOrder();
            }
            
            if (this.authInfo === "appointment") this.handleItemAppointment(); //预约项目
            
            if (this.authInfo?.ggUuid) {
            	this.orderType = "拼团订单";
            	this.handleGoToSpellOrder(this.authInfo); //去拼团页面
            }
            
            if (this.authInfo === "joinGroup") {
            	this.orderType = "参团拼单";
            	this.handleJoinSpellOrder(); //分享后加入拼团
            }
        },

        onAlonePurchase() {
            this.handlePlaceOrder();
        },
        // 订单限购
        async handlePlaceOrder() {
            let userInfo = uni.getStorageSync("userInfo"); // 用户信息
            let count = 0;
            if (userInfo?.isNew === true) {
                if (this.activityItem.giNcby === true) {
                    count = this.activityItem.giNbqu;
                } else uni.showToast({ title: "新客不能购买该项目", icon: "error", duration: 2000 });
            } else {
                if (this.activityItem.giOcby === true) {
                    count = this.activityItem.giObqu;
                } else uni.showToast({ title: "老客不能购买该项目", icon: "error", duration: 2000 });
            }
            let res = await getCustOrderBySoCuidAndSoItem({ soCuid: userInfo?.ciUuid, soItem: this.activityItem?.giUuid });
            if (res.totalCount < count) {
                this.$refs.popup_order.open("bottom");
            } else {
                if (res?.nodes?.findIndex((item) => item.soStat === "待支付") !== -1) {
                    uni.navigateTo({ url: `/pages/my/orders` });
                } else uni.showToast({ title: "您已超过限购次数", icon: "error", duration: 2000 });
            }
        },

        onSpellOrder() {
            this.handlePlaceOrder();
        },

        async handleItemAppointment() {
            let shareId = uni.getStorageSync("shareId") || ""; // 分享人ID
            let staffId = uni.getStorageSync("staffId") || ""; // 员工ID
            let userInfo = uni.getStorageSync("userInfo"); // 用户信息
            const data = {
                gpUuid: this.activityItem.gpUuid,
                giUuid: this.activityItem.giUuid,
                gaBoti: new Date().getUTCTime(),
                gaDisc: this.activityItem.giDicm,
                gaStti: this.activity.gpStti,
                gaEnti: this.activity.gpEnti,
                gaApid: userInfo.ciUuid,
                giBoqu: Number(this.activityItem.giBoqu) + 1,
                // giName: this.activityItem.giName,
                gaStid: staffId || null,
                gaCuid: shareId || null,
            };
            let res = await createItemAppointment(data);
            if (res) {
                this.$store.dispatch("activityInfo/getItemAppointment", {
                    gpUuid: this.activityItem.gpUuid,
                    gaApid: userInfo.ciUuid,
                });
                uni.showToast({
                    title: "预约成功",
                    icon: "success",
                });
            }
        },

        handleGoToSpellOrder(item) {
            let giUuid = this.activityItem.giUuid;
            let gpUuid = this.activity?.gpUuid;
            let ggUuid = item.ggUuid;
            uni.navigateTo({
                url: `/pages/activities/spell_order_detail?giUuid=${giUuid}&gpUuid=${gpUuid}&ggUuid=${ggUuid}`,
            });
        },

        handleJoinSpellOrder() {
            let ggUuid = this.ggUuid;
            let giUuid = this.activityItem.giUuid;
            let gpUuid = this.activity?.gpUuid;
            uni.navigateTo({
                url: `/pages/activities/spell_order_detail?giUuid=${giUuid}&gpUuid=${gpUuid}&ggUuid=${ggUuid}`,
            });
        },

        gotoMoreSpellOrders() {
            uni.navigateTo({
                url: `/pages/activities/spell_order_list?giUuid=${this.activityItem.giUuid}&gpUuid=${this.activity?.gpUuid}`,
            });
        },

        async submitOrderCallback(data) {
            if (!data?.soUuid) return uni.showToast({ title: "没有订单信息", icon: "error" });
            if (data.soType === "单独购买" || data.soType === "新团订单") {
                let spRes = await createActivityItemSpellOrder({ soUuid: data.soUuid });
                if (spRes) {
                    this.$refs.popup_order.close();
                    uni.showToast({
                        title: "支付成功",
                        icon: "success",
                    });
                    if (spRes.ggUuid) {
                        uni.navigateTo({ url: `/pages/activities/spell_order_detail?ggUuid=${spRes.ggUuid}&gpUuid=${this.activityItem?.gpUuid}&giUuid=${this.activityItem.giUuid}` });
                    } else {
                        uni.redirectTo({ url: `/pages/my/orders?giUuid=${this.activityItem.giUuid}&gpUuid=${this.activityItem?.gpUuid}` });
                    }
                }
            }
        },

        closePopup() {
            this.$refs.popup_order.close();
        },

        getActivityItemImage(giPrph) {
            let path = "";
            if (typeof giPrph === "string") path = giPrph;
            else if (Array.isArray(giPrph) && giPrph.length > 1) {
                if (typeof giPrph[0] === "string") path = giPrph[0];
                else {
                    if (new Date().getUTCTime() >= this.activity.gpStti) {
                        const item = giPrph.find((item) => item.display === "3");
                        path = item.path || "";
                    } else {
                        const item = giPrph.find((item) => item.display === "2");
                        path = item.path || "";
                    }
                }
            } else if (Array.isArray(giPrph) && giPrph.length === 1) {
                if (typeof giPrph[0] === "string") {
                    path = giPrph[0];
                } else path = giPrph[0].path || "";
            }
            return path ? this.organizationGateway + "/file/download?filepath=" + path : this.defaultImageBase64;
        },
    },
};
</script>

<style>
page {
    padding-bottom: 55px;
    background-color: #eee;
}
</style>

<style lang="scss" scoped>
page {
    padding-bottom: 55px;
    background-color: #eee;
}

.share-button button {
    background-color: #fff;
    height: 45px;
}

.share-button button::after {
    border: none;
}

.slot-text {
    flex: 1;
    font-size: 14px;
    margin-right: 10px;
}

.swiper-box {
    width: 100%;
    height: 240px;
}

.swiper-box .img {
    width: 100%;
    background-size: cover;
}

.detail-title {
    display: flex;
    background-color: #c1a173;
    height: 30px;
    margin-top: -10px;
    padding: 10px 20px;
}

.mb-title {
    font-weight: 800px;
    font-size: 16px;
    padding: 10px 0 10px 10px;
    background-color: #fff;
}

.detail-share-btn {
    position: absolute;
    right: -6px;
    top: -4px;
    background-color: #c1a173;
    color: #fff;
    border-radius: 20px 0 0 20px;
    margin-right: -13px;
    padding: 5px 5px 5px 5px;
    font-size: 12px;
    width: 60px;
    text-align: center;
}

.store-title {
    margin-top: 5px;
    font-weight: 800px;
    font-size: 12px;
    padding: 5px 0 5px 10px;
    background-color: #fff;
}

.collate-title {
    margin-top: 5px;
    font-weight: 800px;
    font-size: 14px;
    padding: 10px 0 10px 10px;
    background-color: #fff;
    display: flex;
    justify-content: space-between;
}

.actions {
    width: 100%;
    position: fixed;
    bottom: 0;
    height: 50px;
    border-top: 1px solid #eee;
    background-color: #fff;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
}

.actions .item {
    text-align: center;
    font-size: 11px;
}

.actions .menu {
    width: 60px;
}

.actions .bnts {
    display: flex;
}

.share-icon {
    width: 40px;
    height: 40px;
}
</style>
